name: Coverage

on:
  push:
    branches:
      - master
  pull_request: {}

concurrency:
  group: ${{ github.workflow }}-${{ github.ref == 'refs/heads/master' && github.run_number || github.ref }}
  cancel-in-progress: true

jobs:

  coverage:
    runs-on: ubuntu-latest

    # Not intended for forks.
    if: github.repository == 'optuna/optuna'

    steps:
    - name: Checkout
      uses: actions/checkout@v4

    - name: Setup Python3.8
      uses: actions/setup-python@v5
      with:
        python-version: 3.8

    - name: Setup cache
      uses: actions/cache@v3
      env:
        cache-name: coverage
      with:
        path: ~/.cache/pip
        key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/pyproject.toml') }}-v1
        restore-keys: |
          ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('**/pyproject.toml') }}

    - name: Setup environment
      run: |
        sudo apt-get update
        sudo apt-get -y install openmpi-bin libopenmpi-dev libopenblas-dev

    - name: Install
      run: |
        python -m pip install --upgrade pip

        # Install minimal dependencies and confirm that `import optuna` is successful.
        pip install --progress-bar off .
        python -c 'import optuna'
        optuna --version

        pip install --progress-bar off .[test]
        pip install --progress-bar off .[optional] --extra-index-url https://download.pytorch.org/whl/cpu
        # TODO(c-bata): Remove a version constraint after releasing https://github.com/cunla/fakeredis-py/pull/303
        pip install --progress-bar off 'fakeredis[lua]<2.21.2'

        echo 'import coverage; coverage.process_startup()' > sitecustomize.py

    - name: Output installed packages
      run: |
        pip freeze --all
    - name: Output dependency tree
      run: |
        pip install pipdeptree
        pipdeptree


    - name: Tests
      env:
        OMP_NUM_THREADS: 1
        PYTHONPATH: .  # To invoke sitecutomize.py
        COVERAGE_PROCESS_START: .coveragerc  # https://coverage.readthedocs.io/en/6.4.1/subprocess.html
        COVERAGE_COVERAGE: yes  # https://github.com/nedbat/coveragepy/blob/65bf33fc03209ffb01bbbc0d900017614645ee7a/coverage/control.py#L255-L261
      run: |
        coverage run --source=optuna -m pytest tests -m "not skip_coverage and not slow"
        coverage combine
        coverage xml

    - name: Upload coverage to Codecov
      uses: codecov/codecov-action@v3
      with:
        file: ./coverage.xml
